package com.kk.springmvc.demo.common.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.kk.springmvc.demo.common.utils.FastJsonUtils;

/**
 * 统一日志处理
 * 
 * @author chengkai
 * @since 2017/4/1
 *
 */
@Aspect
@Component
public class LogRecordAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogRecordAspect.class);

    @Pointcut("@annotation(com.kk.springmvc.demo.common.anno.LogAround)")
    public void execute() {
    }

    @Around("execute()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        RequestAttributes requestAttrs = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttrs = (ServletRequestAttributes) requestAttrs;
        HttpServletRequest request = servletRequestAttrs.getRequest();

        String url = request.getRequestURL().toString();
        String method = point.getSignature().toString();
        String ip = request.getRemoteAddr();
        int port = request.getRemotePort();
        String queryString = request.getQueryString();
        Object[] params = point.getArgs();

        LOGGER.info("request info, url : {}, mehotd : {}, ip : {}, port : {}, queryString : {}, params : {}", url, method, ip, port, queryString, params);
        Object result = point.proceed();
        LOGGER.info("response info, url : {}, method : {}, ip : {}, port : {}, result : {}", url, method, ip, port, FastJsonUtils.toJSONString(result));
        return result;
    }

}
